package com.yy.jhl.util;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yy.common.baserx.RxManager;
import com.yy.common.commonutils.Base64;
import com.yy.common.commonutils.SPUtils;
import com.yy.common.commonutils.ToastUitl;
import com.yy.jhl.api.Api;
import com.yy.jhl.api.RxSubscriber;
import com.yy.jhl.app.AppConstant;
import com.yy.jhl.bean.FileInfo;
import com.yy.jhl.bean.LoginInfo;
import com.yy.jhl.bean.LogisticsInfo;
import com.yy.jhl.bean.MessageNumInfo;
import com.yy.jhl.bean.ProductInfo;
import com.yy.jhl.interfaces.CommonCallBack;
import com.yy.jhl.interfaces.DoneOrderCallBack;
import com.yy.jhl.interfaces.FileUploadCallBack;
import com.yy.jhl.interfaces.LogisticsCallBack;
import com.yy.jhl.interfaces.MessageNumCallBack;
import com.yy.jhl.interfaces.ProductListCallBack;
import com.yy.jhl.interfaces.UserInfoCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import rx.Observable;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/** 公共请求信息
 * Created by Ellis.Li on 2017/6/21.
 */

public class DataRequestUtil {
    static DataRequestUtil instance;
    static Context mContext;
    static RxManager mRxManage;
    public static DataRequestUtil getInstance(Context cxt){
        mContext = cxt;
        if (instance == null){
            synchronized (DataRequestUtil.class) {
                instance = new DataRequestUtil();
                mRxManage = new RxManager();
            }
        }
        return instance;
    }

    /**
     * 获取当前用户信息
     */
    public  void getUserInfo(final UserInfoCallBack commonCallBack) {
        String uuid = DataUtil.getUserId(mContext);
        mRxManage.addSubscription(Api.getDefault().getUserInfo(uuid), new RxSubscriber<ResponseBody>(mContext,false) {
            @Override
            protected void _onNext(String result) {
                LoginInfo.UserBean userBean = new Gson().fromJson(result,LoginInfo.UserBean.class);
                SPUtils.setSharedObjectData(mContext, AppConstant.SP_KEY_USER_INFO,userBean);
                commonCallBack.getCallBack(userBean);
            }

            @Override
            protected void _onError(String message) {
                commonCallBack.getCallBack(null);
            }
        });
    }

    /**
     * 发送短信验证码
     */
    public  void sendVerificationCode(String phone , final CommonCallBack commonCallBack) {
        RequestBody requestBody = new FormBody.Builder()
                .add("phone", phone)
                .build();
        mRxManage.addSubscription(Api.getDefault().sendCode(requestBody), new RxSubscriber<ResponseBody>(mContext,"发送验证码中...",true) {
            @Override
            protected void _onNext(String result) {
                commonCallBack.getCallBack();
            }

            @Override
            protected void _onError(String message) {
            }
        });
    }
    /**
     * 获取当前消息未读数目
     */
    public  void getUnReadMessageNum(final MessageNumCallBack commonCallBack) {
        mRxManage.addSubscription(Api.getDefault().getMessageUnreadNum(), new RxSubscriber<ResponseBody>(mContext,false,false) {
            @Override
            protected void _onNext(String result) {
                MessageNumInfo messageNumInfo = new Gson().fromJson(result,MessageNumInfo.class);
                commonCallBack.getCallBack(messageNumInfo.getTotal());
            }

            @Override
            protected void _onError(String message) {
                commonCallBack.getCallBack(0);
            }
        });
    }
    /**
     * 文件上传
     * type:1.用户头像 2.企业logo 3.采购合同 4.项目附件 5.产品授权书 6.扫码图片  8小视频
     */
    public  void uploadImage(Context context,final String type,String filePath,final FileUploadCallBack commonCallBack) {
        //上传小视频
        if (type.equals("8")){
            RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), new File(filePath));
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file", filePath, fileBody)
                    .addFormDataPart("type",type)
                    .build();
//            RequestBody requestBody = new FormBody.Builder()
//                    .add("type", type)
//                    .add
//                    .build();
            mRxManage.addSubscription(Api.getDefault().uploadImage(requestBody), new RxSubscriber<ResponseBody>(mContext,"上传中",false) {
                @Override
                protected void _onNext(String result) {
                    //                ToastUitl.showShort("文件上传成功");
                    FileInfo fileInfo = new Gson().fromJson(result,FileInfo.class);
                    commonCallBack.success(fileInfo);
                }

                @Override
                protected void _onError(String message) {
                    ToastUitl.showShort("上传失败，请重新上传！");
                    commonCallBack.fail();
                }
            });
        }else {
            Luban.with(context)
                    .load(filePath)                                   // 传人要压缩的图片列表
                    .ignoreBy(40)                                  // 忽略不压缩图片的大小
                    .setTargetDir(Configuration.getUserImageDirectoryPath())                        // 设置压缩后文件存储位置
                    .setCompressListener(new OnCompressListener() { //设置回调

                        @Override
                        public void onStart() {
                            // TODO 压缩开始前调用，可以在方法内启动 loading UI
                        }

                        @Override
                        public void onSuccess(File file) {
                            // TODO 压缩成功后调用，返回压缩后的图片文件
                            String file64 = null;
                            try {
                                file64 = Base64.encodeFromFile(file.getAbsolutePath());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            RequestBody requestBody = new FormBody.Builder()
                                    .add("type", type)
                                    .add("file", file64)
                                    .add("uptype", "base64")
                                    .build();
                            mRxManage.addSubscription(Api.getDefault().uploadImage(requestBody), new RxSubscriber<ResponseBody>(mContext,"上传中",false) {
                                @Override
                                protected void _onNext(String result) {
    //                ToastUitl.showShort("文件上传成功");
                                    FileInfo fileInfo = new Gson().fromJson(result,FileInfo.class);
                                    commonCallBack.success(fileInfo);
                                }

                                @Override
                                protected void _onError(String message) {
                                    ToastUitl.showShort("上传失败，请重新上传！");
                                    commonCallBack.fail();
                                }
                            });
                        }

                        @Override
                        public void onError(Throwable e) {
                            // TODO 当压缩过程出现问题时调用
                        }
                    }).launch();    //启动压缩
        }

    }

    /**
     * 采购商完结项目
     */
    public  void cgsDoneOrder(String project_id ,String status, final int position,final DoneOrderCallBack commonCallBack) {
        RequestBody requestBody = new FormBody.Builder()
                .add("project_id", project_id)
                .add("status", status)
                .build();
        mRxManage.addSubscription(Api.getDefault().cgsDoneOrder(requestBody), new RxSubscriber<ResponseBody>(mContext,true) {
            @Override
            protected void _onNext(String result) {
                commonCallBack.getCallBack(position);
            }

            @Override
            protected void _onError(String message) {
            }
        });
    }
    /**
     * 删除产品
     */
    public  void removePackage(String package_id ,final CommonCallBack commonCallBack) {
        RequestBody requestBody = new FormBody.Builder()
                .add("package_id", package_id)
                .build();
        mRxManage.addSubscription(Api.getDefault().removePackage(requestBody), new RxSubscriber<ResponseBody>(mContext,true) {
            @Override
            protected void _onNext(String result) {
                commonCallBack.getCallBack();
            }

            @Override
            protected void _onError(String message) {
            }
        });
    }
    /**
     * 产品列表
     */
    public  void getProductList(String batchId,String packageId ,final ProductListCallBack commonCallBack) {
        mRxManage.addSubscription(Api.getDefault().getBoxPackageList(batchId,packageId), new RxSubscriber<ResponseBody>(mContext,true) {
            @Override
            protected void _onNext(String result) {
                List<ProductInfo> retList = new Gson().fromJson(result,
                        new TypeToken<List<ProductInfo>>() {
                        }.getType());
                commonCallBack.getCallBack(retList);
            }

            @Override
            protected void _onError(String message) {
            }
        });
    }
    /**
     * 审核
     */
    public  void flowCheck(String batch_id ,int ship_status,int status,String remark,final CommonCallBack commonCallBack) {
        RequestBody requestBody = new FormBody.Builder()
                .add("batch_id", batch_id)
                .add("ship_status",ship_status+"")
                .add("status", status+"")
                .add("remark", remark)
                .build();
        mRxManage.addSubscription(Api.getDefault().cgsChuKuCheck(requestBody), new RxSubscriber<ResponseBody>(mContext,true) {
            @Override
            protected void _onNext(String result) {
                commonCallBack.getCallBack();
            }

            @Override
            protected void _onError(String message) {
            }
        });
    }

    /**
     * 获取物流监管信息
     * @param batchId
     */
    public void getLogisticsInfo(String batchId, final LogisticsCallBack logisticsCallBack) {
        mRxManage.addSubscription(Api.getDefault().cgsGetJGBatchDetail(batchId), new RxSubscriber<ResponseBody>(mContext,true) {
            @Override
            protected void _onNext(String result) {
                LogisticsInfo projectInfo = new Gson().fromJson(result,LogisticsInfo.class);
                logisticsCallBack.getCallBack(projectInfo);
            }

            @Override
            protected void _onError(String message) {
            }
        });
    }
    /**
     * 发送短信验证码
     */
    public  void collectProject(String project_id , final boolean isCollected, final CommonCallBack commonCallBack) {
        RequestBody requestBody = new FormBody.Builder()
                .add("project_id", project_id)
                .build();
        Observable<ResponseBody> obs;
        if (isCollected){
            obs = Api.getDefault().removeCollect(requestBody);
        }else {
            obs = Api.getDefault().addCollect(requestBody);
        }
        mRxManage.addSubscription(obs, new RxSubscriber<ResponseBody>(mContext,true) {
            @Override
            protected void _onNext(String result) {
                if (isCollected){
                    ToastUitl.showShort("已取消收藏");
                }else {
                    ToastUitl.showShort("已收藏");
                }
                commonCallBack.getCallBack();
            }

            @Override
            protected void _onError(String message) {
            }
        });
    }
}
